<!DOCTYPE html>

































































<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>Fragments | Android Developers</title>
<link href="../../../assets/android-developer-docs-devguide.css" rel="stylesheet" type="text/css" />
<script src="../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../assets/android-developer-docs.js" type="text/javascript"></script>
<script src="../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
  setToRoot("../../../");
</script>
<noscript>
  <style type="text/css">
    html,body{overflow:auto;}
    #body-content{position:relative; top:0;}
    #doc-content{overflow:visible;border-left:3px solid #666;}
    #side-nav{padding:0;}
    #side-nav .toggle-list ul {display:block;}
    #resize-packages-nav{border-bottom:3px solid #666;}
  </style>
</noscript>
</head>
<body class="gc-documentation">

  <div id="header">
      <div id="headerLeft">
          <a href="../../../index.html" tabindex="-1"><img
              src="../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
          <ul id="header-tabs" class="guide">
    
	<li id="home-link"><a href="../../../offline.html">
	
		<span class="en">Home</span>
		<span style="display:none" class="de">Startseite</span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ホーム</span>
		<span style="display:none" class="zh-CN">主页</span>
		<span style="display:none" class="zh-TW">首頁</span>
	
	</a></li>
	<li id="sdk-link"><a href="../../../sdk/index.html">
		<span class="en">SDK</span>
	</a></li>
	<li id="guide-link"><a href="../../../guide/index.html" onClick="return loadLast('guide')">
	
		<span class="en">Dev Guide</span>
		<span style="display:none" class="de">Handbuch</span>
		<span style="display:none" class="es">Guía</span>
		<span style="display:none" class="fr">Guide</span>
		<span style="display:none" class="it">Guida</span>
		<span style="display:none" class="ja">開発ガイド</span>
		<span style="display:none" class="zh-CN">开发人员指南</span>
		<span style="display:none" class="zh-TW">開發指南</span>
	
	</a></li>
	<li id="reference-link"><a href="../../../reference/packages.html" onClick="return loadLast('reference')">
	
		<span class="en">Reference</span>
		<span style="display:none" class="de">Referenz</span>
		<span style="display:none" class="es">Referencia</span>
		<span style="display:none" class="fr">Référence</span>
		<span style="display:none" class="it">Riferimento</span>
		<span style="display:none" class="ja">リファレンス</span>
		<span style="display:none" class="zh-CN">参考</span>
		<span style="display:none" class="zh-TW">參考資料</span>
	
	</a></li>
	<li id="resources-link"><a href="../../../resources/index.html" onClick="return loadLast('resources')">
	
		<span class="en">Resources</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
    		<span style="display:none" class="ja"></span>
		<span style="display:none" class="zh-CN"></span>
		<span style="display:none" class="zh-TW"></span>
	
	</a></li>
	<li id="videos-link"><a href="../../../videos/index.html" onClick="return loadLast('videos')">
	
		<span class="en">Videos</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ビデオ</span>
		<span style="display:none" class="zh-CN"></span>
		<span style="display:none" class="zh-TW"></span>
	
	</a></li>
	<li><a href="http://android-developers.blogspot.com" onClick="return requestAppendHL(this.href)">
	
		<span class="en">Blog</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ブログ</span>
		<span style="display:none" class="zh-CN">博客</span>
		<span style="display:none" class="zh-TW">網誌</span>
	
	</a></li>


     
</ul>
     
      </div>
      <div id="headerRight">
          <div id="headerLinks">
          
          <a href="http://www.android.com">Android.com</a>
          </div>
  <div id="search" >
      <div id="searchForm">
          <form accept-charset="utf-8" class="gsc-search-box" 
                onsubmit="return submit_search()">
            <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
                <tr>
                  <td class="gsc-input">
                    <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
                      title="search developer docs" name="q"
                      value="search developer docs"
                      onFocus="search_focus_changed(this, true)"
                      onBlur="search_focus_changed(this, false)"
                      onkeydown="return search_changed(event, true, '../../../')"
                      onkeyup="return search_changed(event, false, '../../../')" />
                  <div id="search_filtered_div" class="no-display">
                      <table id="search_filtered" cellspacing=0>
                      </table>
                  </div>
                  </td>
                  <td class="gsc-search-button">
                    <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
                  </td>
                  <td class="gsc-clear-button">
                    <div title="clear results" class="gsc-clear-button">&nbsp;</div>
                  </td>
                </tr></tbody>
              </table>
          </form>
      </div><!-- searchForm -->
  </div><!-- search -->
      </div><!-- headerRight -->
      <script type="text/javascript">
        <!--  
        changeTabLang(getLangPref());
        //-->
      </script>
  </div><!-- header -->

  <div class="g-section g-tpl-240" id="body-content">
    <div class="g-unit g-first" id="side-nav">
      <div id="devdoc-nav">
<ul>

  <li>
    <h2><span class="en">Android Basics</span>
        <span class="de" style="display:none">Einführung in Android</span>
        <span class="es" style="display:none">Información básica sobre Android</span>
        <span class="fr" style="display:none">Présentation d'Android</span>
        <span class="it" style="display:none">Nozioni di base su Android</span>
        <span class="ja" style="display:none">Android の基本</span>
        <span class="zh-CN" style="display:none">Android 基础知识</span>
        <span class="zh-TW" style="display:none">Android 簡介</span>
    </h2>
    <ul>
      <li><a href="../../../guide/basics/what-is-android.html">
        <span class="en">What Is Android?</span>
        <span class="de" style="display:none">Was ist Android?</span>
        <span class="es" style="display:none">¿Qué es Android?</span>
        <span class="fr" style="display:none">Qu'est-ce qu'Android&nbsp;?</span>
        <span class="it" style="display:none">Che cos'è Android?</span>
        <span class="ja" style="display:none">Android とは</span>
        <span class="zh-CN" style="display:none">Android 是什么？</span>
        <span class="zh-TW" style="display:none">什麼是 Android？</span>
          </a></li>
      <li><a href="../../../guide/topics/fundamentals.html">
        <span class="en">Application Fundamentals</span>
        <span class="de" style="display:none">Anwendungsgrundlagen</span>
        <span class="es" style="display:none">Fundamentos de las aplicaciones</span>
        <span class="fr" style="display:none">Principes de base des applications</span>
        <span class="it" style="display:none">Concetti fondamentali sulle applicazioni</span>
        <span class="ja" style="display:none">開発の基礎</span>
        <span class="zh-CN" style="display:none">应用程序基础</span>
        <span class="zh-TW" style="display:none">應用程式基本原理</span>
      </a></li>

  <!--  <li><a style="color:gray;">The Android SDK</a></li> -->
  <!--  <li><a style="color:gray;">Walkthrough for Developers</a></li> -->
      <!-- quick overview of what it's like to develop on Android -->
    </ul>
  </li>

  <li>
    <h2>
      <span class="en">Framework Topics</span>
      <span class="de" style="display:none">Framework-Themen</span>
      <span class="es" style="display:none">Temas sobre el framework</span>
      <span class="fr" style="display:none">Thèmes relatifs au framework</span>
      <span class="it" style="display:none">Argomenti relativi al framework</span>
      <span class="ja" style="display:none">フレームワーク トピック</span>
      <span class="zh-CN" style="display:none">框架主题</span>
      <span class="zh-TW" style="display:none">架構主題</span>
    </h2>
    <ul>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/fundamentals/activities.html">
          <span class="en">Activities</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/fundamentals/fragments.html">
            <span class="en">Fragments</span>
          </a></li>
          <li><a href="../../../guide/topics/fundamentals/loaders.html">
            <span class="en">Loaders</span>
          </a></li>
          <li><a href="../../../guide/topics/fundamentals/tasks-and-back-stack.html">
            <span class="en">Tasks and Back Stack</span></a></li>
        </ul>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/fundamentals/services.html">
          <span class="en">Services</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/fundamentals/bound-services.html">
            <span class="en">Bound Services</span>
          </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/topics/providers/content-providers.html">
            <span class="en">Content Providers</span>
          </a></li>
      <li><a href="../../../guide/topics/intents/intents-filters.html">
            <span class="en">Intents and Intent Filters</span>
          </a></li>
      <li><a href="../../../guide/topics/fundamentals/processes-and-threads.html">
            <span class="en">Processes and Threads</span>
          </a></li>
    </ul>


    <ul>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/ui/index.html">
            <span class="en">User Interface</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/topics/ui/declaring-layout.html">
               <span class="en">XML Layouts</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/ui-events.html">
                <span class="en">Input Events</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/menus.html">
               <span class="en">Menus</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/actionbar.html">
               <span class="en">Action Bar</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/dialogs.html">
                <span class="en">Dialogs</span>
              </a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/topics/ui/notifiers/index.html">
                <span class="en">Notifications</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/topics/ui/notifiers/toasts.html">
                <span class="en">Toast Notifications</span>
              </a></li>
              <li><a href="../../../guide/topics/ui/notifiers/notifications.html">
                <span class="en">Status Bar Notifications</span>
              </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/topics/ui/drag-drop.html">
                <span class="en">Drag and Drop</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/themes.html">
                <span class="en">Styles and Themes</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/custom-components.html">
                <span class="en">Custom Components</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/binding.html">
                <span class="en">Binding to Data with AdapterView</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/layout-objects.html">
                <span class="en">Common Layout Objects</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/how-android-draws.html">
                <span class="en">How Android Draws Views</span>
              </a></li>
        </ul>
      </li><!-- end of User Interface -->

      <li class="toggle-list">
        <div><a href="../../../guide/topics/resources/index.html">
               <span class="en">Application Resources</span>
             </a></div>
        <ul>
          <li><a href="../../../guide/topics/resources/providing-resources.html">
                <span class="en">Providing Resources</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/accessing-resources.html">
                <span class="en">Accessing Resources</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/runtime-changes.html">
                <span class="en">Handling Runtime Changes</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/localization.html">
                <span class="en">Localization</span>
              </a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/topics/resources/available-resources.html">
              <span class="en">Resource Types</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/topics/resources/animation-resource.html">Animation</a></li>
              <li><a href="../../../guide/topics/resources/color-list-resource.html">Color State List</a></li>
              <li><a href="../../../guide/topics/resources/drawable-resource.html">Drawable</a></li>
              <li><a href="../../../guide/topics/resources/layout-resource.html">Layout</a></li>
              <li><a href="../../../guide/topics/resources/menu-resource.html">Menu</a></li>
              <li><a href="../../../guide/topics/resources/string-resource.html">String</a></li>
              <li><a href="../../../guide/topics/resources/style-resource.html">Style</a></li>
              <li><a href="../../../guide/topics/resources/more-resources.html">More Types</a></li>
            </ul>
          </li><!-- end of resource types -->
        </ul>
      </li><!-- end of app resources -->
      <li class="toggle-list">
        <div><a href="../../../guide/topics/data/data-storage.html">
            <span class="en">Data Storage</span>
          </a></div>
          <ul>
            <li><a href="../../../guide/topics/data/backup.html">
                <span class="en">Data Backup</span>
              </a>
            </li>
          </ul>
      </li>
      <li><a href="../../../guide/topics/security/security.html">
            <span class="en">Security and Permissions</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/manifest/manifest-intro.html">
          <span class="en">The AndroidManifest.xml File</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/manifest/action-element.html">&lt;action&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/activity-alias-element.html">&lt;activity-alias&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/application-element.html">&lt;application&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/category-element.html">&lt;category&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/compatible-screens-element.html">&lt;compatible-screens&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/data-element.html">&lt;data&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/grant-uri-permission-element.html">&lt;grant-uri-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/instrumentation-element.html">&lt;instrumentation&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/intent-filter-element.html">&lt;intent-filter&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/manifest-element.html">&lt;manifest&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/path-permission-element.html">&lt;path-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-element.html">&lt;permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-group-element.html">&lt;permission-group&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-tree-element.html">&lt;permission-tree&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/service-element.html">&lt;service&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/supports-gl-texture-element.html">&lt;supports-gl-texture&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></li><!-- ##api level 4## -->
          <li><a href="../../../guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></li> <!-- ##api level 4## -->
          <li><a href="../../../guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a></li>
        </ul>
      </li><!-- end of the manifest file -->
    </ul>

    <ul>
    <li class="toggle-list">
        <div><a href="../../../guide/topics/graphics/index.html">
            <span class="en">Graphics</span>
          </a><span class="new-child">new!</span></div>
        <ul>
          <li><a href="../../../guide/topics/graphics/2d-graphics.html">
              <span class="en">Canvas and Drawables</span></a></li>
          <li><a href="../../../guide/topics/graphics/hardware-accel.html">
              <span class="en">Hardware Acceleration</span></a>
            <span class="new">new!</span></li>
          <li><a href="../../../guide/topics/graphics/opengl.html">
              <span class="en">OpenGL</span>
            </a><span class="new">updated</span></li>
        </ul>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/graphics/animation.html">
            <span class="en">Animation</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/topics/graphics/prop-animation.html">
              <span class="en">Property Animation</span></a></li>
          <li><a href="../../../guide/topics/graphics/view-animation.html">
              <span class="en">View Animation</span></a></li>
          <li><a href="../../../guide/topics/graphics/drawable-animation.html">
              <span class="en">Drawable Animation</span></a></li>
        </ul>
      </li>
      <li class="toggle-list">
	        <div><a href="../../../guide/topics/renderscript/index.html">
	            <span class="en">RenderScript</span>
	          </a></div>
	        <ul>
	          <li><a href="../../../guide/topics/renderscript/graphics.html">
	                <span class="en">Graphics</span>
	              </a>
	          </li>
	          <li><a href="../../../guide/topics/renderscript/compute.html">
	                <span class="en">Compute</span>
	              </a>
	          </li>
	        </ul>
  	  </li>

      <li class="toggle-list">
          <div><a href="../../../guide/topics/media/index.html">
            <span class="en">Multimedia and Camera</span>
          </a><span class="new">updated</span></div>
          <ul>
            <li><a href="../../../guide/topics/media/mediaplayer.html">
                  <span class="en">Media Playback</span></a>
                </li>
            <li><a href="../../../guide/topics/media/jetplayer.html">
                  <span class="en">JetPlayer</span></a>
                </li>
            <li><a href="../../../guide/topics/media/camera.html">
                  <span class="en">Camera</span></a>
                  <span class="new">new!</span>
                </li>
            <li><a href="../../../guide/topics/media/audio-capture.html">
                  <span class="en">Audio Capture</span></a>
                </li>
          </ul>
      </li>
      <li>
        <a href="../../../guide/topics/clipboard/copy-paste.html">
            <span class="en">Copy and Paste</span>
        </a></li>
  <!--<li class="toggle-list">
        <div><a style="color:gray;">Sensors</a></div>
          <ul>
            <li><a style="color:gray;">Camera</a></li>
            <li><a style="color:gray;">Compass</a></li>
            <li><a style="color:gray;">Accelerometer</a></li>
          </ul>
      </li> -->
      <li class="toggle-list">
        <div><a href="../../../guide/topics/location/index.html">
               <span class="en">Location and Maps</span>
             </a></div>
        <ul>
          <li><a href="../../../guide/topics/location/obtaining-user-location.html">
                <span class="en">Obtaining User Location</span>
              </a></li>
        </ul>
      </li>
  <!--<li class="toggle-list">
        <div><a style="color:gray;">Wireless Controls</a></div>
          <ul>
            <li><a style="color:gray;">Wi-Fi</a></li>
          </ul>
      </li> -->
  <!--<li><a style="color:gray;">Localization</a></li>  -->
      <li><a href="../../../guide/topics/appwidgets/index.html">
            <span class="en">App Widgets</span></a>
          </li>
      <li><a href="../../../guide/topics/wireless/bluetooth.html">
            <span class="en">Bluetooth</span></a>
          </li>
      <li><a href="../../../guide/topics/nfc/index.html">
            <span class="en">Near Field Communication</span>
          </a></li>
      <li class="toggle-list">
          <div><a href="../../../guide/topics/usb/index.html">
            <span class="en">USB</span></a>
          </div>
            <ul>
              <li><a href="../../../guide/topics/usb/accessory.html">Accessory</a></li>
              <li><a href="../../../guide/topics/usb/host.html">Host</a></li>
              <li><a href="../../../guide/topics/usb/adk.html">Open Accessory Dev Kit</a></li>
            </ul>
          </li>

       <li><a href="../../../guide/topics/network/sip.html">
            <span class="en">Session Initiation Protocol</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/search/index.html">
            <span class="en">Search</span>
          </a></div>
          <ul>
            <li><a href="../../../guide/topics/search/search-dialog.html">Creating a Search Interface</a></li>
            <li><a href="../../../guide/topics/search/adding-recent-query-suggestions.html">Adding Recent Query Suggestions</a></li>
            <li><a href="../../../guide/topics/search/adding-custom-suggestions.html">Adding Custom Suggestions</a></li>
            <li><a href="../../../guide/topics/search/searchable-config.html">Searchable Configuration</a></li>
          </ul>
      </li>
      <li><a href="../../../guide/topics/admin/device-admin.html">
            <span class="en">Device Administration</span></a>
      </li>
      <li class="toggle-list">
           <div>
                <a href="../../../guide/topics/testing/index.html">
                   <span class="en">Testing</span>
               </a>
           </div>
           <ul>
              <li>
                <a href="../../../guide/topics/testing/testing_android.html">
                <span class="en">Testing Fundamentals</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/activity_testing.html">
                <span class="en">Activity Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/contentprovider_testing.html">
                <span class="en">Content Provider Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/service_testing.html">
                <span class="en">Service Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/what_to_test.html">
                <span class="en">What To Test</span></a>
              </li>
           </ul>
      </li>
    </ul>
  </li>

  <li>
    <h2>
      <span class="en">Android Market Topics</span>
    </h2>
    <ul>
      <li><a href="../../../guide/publishing/licensing.html">
          <span class="en">Application Licensing</span></a>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/market/billing/index.html">
            <span class="en">In-app Billing</span></a>
        </div>
        <ul>
          <li><a href="../../../guide/market/billing/billing_overview.html">
              <span class="en">In-app Billing Overview</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_integrate.html">
              <span class="en">Implementing In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_best_practices.html">
              <span class="en">Security and Design</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_testing.html">
              <span class="en">Testing In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_admin.html">
              <span class="en">Administering In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_reference.html">
              <span class="en">In-app Billing Reference</span></a>
          </li>
        </ul>
      </li>
      <li><a href="../../../guide/appendix/market-filters.html">
          <span class="en">Market Filters</span></a>
      </li>
      <li><a href="../../../guide/market/publishing/multiple-apks.html">
          <span class="en">Multiple APK Support</span></a>
      </li>
    </ul>
  </li>


  <li>
    <h2><span class="en">Developing</span>
               <span class="de" style="display:none">Entwicklung</span>
               <span class="es" style="display:none">Desarrollo</span>
               <span class="fr" style="display:none">Développement</span>
               <span class="it" style="display:none">Sviluppo</span>
               <span class="ja" style="display:none">開発</span>
               <span class="zh-CN" style="display:none">开发</span>
               <span class="zh-TW" style="display:none">開發</span>
    </h2>
    <ul>
  <!--<li><a href="">Developing for Android</a></li>
      signing, upgrading, selecting a package name, select device profile, touch, trackball, dpad available, etc. -->
      <li>
        <a href="../../../guide/developing/index.html">
        <span class="en">Introduction</span></a>
      </li>

      <li class="toggle-list">
        <div>
           <a href="../../../guide/developing/devices/index.html">
                <span class="en">Managing Virtual Devices</span>
            </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/devices/managing-avds.html">
              <span class="en">With AVD Manager</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/devices/managing-avds-cmdline.html">
              <span class="en">From the Command Line</span>
            </a>
          </li>
          <li>
           <a href="../../../guide/developing/devices/emulator.html">
                <span class="en">Using the Android Emulator</span>
            </a>
          </li>
        </ul>
      </li>
      <li>
        <a href="../../../guide/developing/device.html">
          <span class="en">Using Hardware Devices</span>
        </a>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/projects/index.html">
            <span class="en">Managing Projects</span>
          </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/projects/projects-eclipse.html">
              <span class="en">From Eclipse with ADT</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/projects/projects-cmdline.html">
                <span class="en">From the Command Line</span>
            </a>
          </li>
        </ul>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/building/index.html">
            <span class="en">Building and Running</span>
          </a>
        </div>
        <ul>
          <li><a href="../../../guide/developing/building/building-eclipse.html">
            <span class="en">From Eclipse with ADT</span>
          </a></li>
          <li><a href="../../../guide/developing/building/building-cmdline.html">
            <span class="en">From the Command Line</span></a></li>
        </ul>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/debugging/index.html">
            <span class="en">Debugging</span>
          </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/debugging/debugging-projects.html">
                <span class="en">From Eclipse with ADT</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-projects-cmdline.html">
                <span class="en">From Other IDEs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/ddms.html">
              <span class="en">Using DDMS</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-log.html">
                <span class="en">Reading and Writing Logs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-ui.html">
                <span class="en">Debugging and Profiling UIs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-tracing.html">
                <span class="en">Profiling with Traceview and dmtracedump</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-devtools.html">
                <span class="en">Using the Dev Tools App</span>
            </a>
          </li>
        </ul>
      </li>

      <li class="toggle-list">
           <div>
                <a href="../../../guide/developing/testing/index.html">
                   <span class="en">Testing</span>
               </a>
           </div>
           <ul>
              <li>
                <a href="../../../guide/developing/testing/testing_eclipse.html">
                  <span class="en">From Eclipse with ADT</span>
                </a>
              </li>

              <li>
                <a href="../../../guide/developing/testing/testing_otheride.html">
                  <span class="en">From Other IDEs</span>
                </a>
              </li>
           </ul>
         </li>

         <li class="toggle-list">
        <div><a href="../../../guide/developing/tools/index.html">
            <span class="en">Tools</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/developing/tools/adb.html">adb</a></li>
          <li><a href="../../../guide/developing/tools/adt.html">ADT</a></li>
          <li><a href="../../../guide/developing/tools/android.html">android</a></li>
          <li><a href="../../../guide/developing/tools/bmgr.html">bmgr</a>
          <li><a href="../../../guide/developing/tools/dmtracedump.html">dmtracedump</a></li>
          <li><a href="../../../guide/developing/tools/draw9patch.html">Draw
          9-Patch</a></li>
          <li><a href="../../../guide/developing/tools/emulator.html">Emulator</a></li>
          <li><a href="../../../guide/developing/tools/etc1tool.html">etc1tool</a></li>
          <li><a href="../../../guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a></li>
          <li><a href="../../../guide/developing/tools/hprof-conv.html">hprof-conv</a></li>
          <li><a href="../../../guide/developing/tools/layoutopt.html">layoutopt</a></li>
          <li><a href="../../../guide/developing/tools/logcat.html">logcat</a></li>
          <li><a href="../../../guide/developing/tools/mksdcard.html">mksdcard</a></li>
          <li><a href="../../../guide/developing/tools/monkey.html">Monkey</a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/developing/tools/monkeyrunner_concepts.html">
              <span class="en">monkeyrunner</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/developing/tools/MonkeyDevice.html">
                <span class="en">MonkeyDevice</span>
                </a></li>
              <li><a href="../../../guide/developing/tools/MonkeyImage.html">
                <span class="en">MonkeyImage</span>
                </a></li>
              <li><a href="../../../guide/developing/tools/MonkeyRunner.html">
                <span class="en">MonkeyRunner</span>
                </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/developing/tools/proguard.html">ProGuard</a></li>
          <li><a href="../../../guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
          <li><a href="../../../guide/developing/tools/traceview.html">Traceview</a></li>
          <li><a href="../../../guide/developing/tools/zipalign.html">zipalign</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Publishing</span>
        <span class="de" style="display:none">Veröffentlichung</span>
        <span class="es" style="display:none">Publicación</span>
        <span class="fr" style="display:none">Publication</span>
        <span class="it" style="display:none">Pubblicazione</span>
        <span class="ja" style="display:none">公開</span>
        <span class="zh-CN" style="display:none">发布</span>
        <span class="zh-TW" style="display:none">發佈</span>
    </h2>
    <ul>
      <li><a href="../../../guide/publishing/app-signing.html">
            <span class="en">Signing Your Applications</span>
            <span class="de" style="display:none">Signieren Ihrer Anwendungen</span>
            <span class="es" style="display:none">Firma de aplicaciones</span>
            <span class="fr" style="display:none">Attribution de votre signature <br />à vos applications</span>
            <span class="it" style="display:none">Firma delle applicazioni</span>
            <span class="ja" style="display:none">アプリケーションへの署名</span>
            <span class="zh-CN" style="display:none">应用程序签名</span>
            <span class="zh-TW" style="display:none">簽署應用程式</span>
          </a></li>
      <li><a href="../../../guide/publishing/versioning.html">
            <span class="en">Versioning Your Applications</span>
            <span class="de" style="display:none">Versionsverwaltung für Ihre <br />Anwendungen</span>
            <span class="es" style="display:none">Versiones de las aplicaciones</span>
            <span class="fr" style="display:none">Attribution d'une version à vos applications</span>
            <span class="it" style="display:none">Controllo versioni delle applicazioni</span>
            <span class="ja" style="display:none">アプリケーションのバージョニング</span>
            <span class="zh-CN" style="display:none">应用程序版本控制</span>
            <span class="zh-TW" style="display:none">應用程式版本設定</span>
          </a></li>
      <li><a href="../../../guide/publishing/preparing.html">
            <span class="en">Preparing to Publish</span>
            <span class="de" style="display:none">Vorbereitung auf die Veröffentlichung</span>
            <span class="es" style="display:none">Publicación de aplicaciones</span>
            <span class="fr" style="display:none">Préparation à la publication</span>
            <span class="it" style="display:none">Preparativi per la pubblicazione</span>
            <span class="ja" style="display:none">公開の準備</span>
            <span class="zh-CN" style="display:none">准备发布</span>
            <span class="zh-TW" style="display:none">準備發佈</span>
          </a></li>
      <li><a href="../../../guide/publishing/publishing.html">
            <span class="en">Publishing on Android Market</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Best Practices</span>
               <span class="de" style="display:none">Bewährte Verfahren</span>
               <span class="es" style="display:none">Prácticas recomendadas</span>
               <span class="fr" style="display:none">Meilleures pratiques</span>
               <span class="it" style="display:none">Best practice</span>
               <span class="ja" style="display:none">ベスト プラクティス</span>
               <span class="zh-CN" style="display:none">最佳实践</span>
               <span class="zh-TW" style="display:none">最佳實務</span>
    </h2>
    <ul>
      <li><a href="../../../guide/practices/compatibility.html">
            <span class="en">Compatibility</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/screens_support.html">
          <span class="en">Supporting Multiple Screens</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/practices/screens-distribution.html">
            <span class="en">Distributing to Specific Screens</span>
          </a></li>
          <li><a href="../../../guide/practices/screen-compat-mode.html">
            <span class="en">Screen Compatibility Mode</span>
          </a></li>
          <li><a href="../../../guide/practices/screens-support-1.5.html">
            <span class="en">Strategies for Android 1.5</span>
          </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/practices/optimizing-for-3.0.html">
            <span class="en">Optimizing Apps for Android 3.0</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/ui_guidelines/index.html">
               <span class="en">UI Guidelines</span>
             </a></div>
        <ul>
          <li class="toggle-list">
            <div><a href="../../../guide/practices/ui_guidelines/icon_design.html">
                   <span class="en">Icon Design <span class="new">updated</span></span>
                 </a></div>
            <ul>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_launcher.html">
                    <span class="en">Launcher Icons <span class="new">updated</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_menu.html">
                    <span class="en">Menu Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_action_bar.html">
                    <span class="en">Action Bar Icons <span class="new">new!</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_status_bar.html">
                    <span class="en">Status Bar Icons <span class="new">updated</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_tab.html">
                    <span class="en">Tab Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_dialog.html">
                    <span class="en">Dialog Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_list.html">
                    <span class="en">List View Icons</span>
                  </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/practices/ui_guidelines/widget_design.html">
                <span class="en">App Widget Design <span class="new">updated</span></span>
              </a></li>
          <li><a href="../../../guide/practices/ui_guidelines/activity_task_design.html">
                <span class="en">Activity and Task Design</span>
              </a></li>
          <li><a href="../../../guide/practices/ui_guidelines/menu_design.html">
                <span class="en">Menu Design</span>
              </a></li>
        </ul>
      </li>
      </ul>
      <ul>
      <li><a href="../../../guide/practices/design/accessibility.html">
            <span class="en">Designing for Accessibility</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/design/performance.html">
            <span class="en">Designing for Performance</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/practices/design/jni.html">
                <span class="en">JNI Tips</span>
              </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/practices/design/responsiveness.html">
            <span class="en">Designing for Responsiveness</span>
          </a></li>
      <li><a href="../../../guide/practices/design/seamlessness.html">
            <span class="en">Designing for Seamlessness</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Web Applications</span>
    </h2>
    <ul>
      <li><a href="../../../guide/webapps/index.html">
            <span class="en">Web Apps Overview</span>
          </a></li>
      <li><a href="../../../guide/webapps/targeting.html">
            <span class="en">Targeting Screens from Web Apps</span>
          </a></li>
      <li><a href="../../../guide/webapps/webview.html">
            <span class="en">Building Web Apps in WebView</span>
          </a></li>
      <li><a href="../../../guide/webapps/debugging.html">
            <span class="en">Debugging Web Apps</span>
          </a></li>
      <li><a href="../../../guide/webapps/best-practices.html">
            <span class="en">Best Practices for Web Apps</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Appendix</span>
               <span class="de" style="display:none">Anhang</span>
               <span class="es" style="display:none">Apéndice</span>
               <span class="fr" style="display:none">Annexes</span>
               <span class="it" style="display:none">Appendice</span>
               <span class="ja" style="display:none">付録</span>
               <span class="zh-CN" style="display:none">附录</span>
               <span class="zh-TW" style="display:none">附錄</span>
    </h2>
    <ul>
      <li><a href="../../../guide/appendix/api-levels.html">
            <span class="en">Android API Levels</span>
          </a></li>
      <li><a href="../../../guide/appendix/install-location.html">
            <span class="en">App Install Location</span>
          </a></li>
      <li><a href="../../../guide/appendix/media-formats.html">
            <span class="en">Supported Media Formats <span class="new">updated</span></span>
          </a></li>
      <li><a href="../../../guide/appendix/g-app-intents.html">
            <span class="en">Intents List: Google Apps</span>
          </a></li>
      <li><a href="../../../guide/developing/tools/aidl.html">AIDL</a></li>
      <li><a href="../../../guide/appendix/glossary.html">
            <span class="en">Glossary</span>
          </a></li>
    </ul>
  </li>

</ul>

<script type="text/javascript">
<!--
    buildToggleLists();
    changeNavLang(getLangPref());
//-->
</script>

      </div>
    </div> <!-- end side-nav -->
    <script>
      addLoadEvent(function() {
        scrollIntoView("devdoc-nav");
        });
    </script>




<div class="g-unit" id="doc-content"><a name="top"></a>

<div id="jd-header" class="guide-header">
  <span class="crumb">
    
      <a href="activities.html">Activities</a> >
    
  </span>
<h1>Fragments 碎片</h1>
</div>

  <div id="jd-content">

    <div class="jd-descr">
    <div id="qv-wrapper">
<div id="qv">

  <h2>Quickview</h2>
  <ul>
    <li>Fragments decompose application functionality and UI into reusable modules</li>
    <li>Add multiple fragments to a screen to avoid switching activities</li>
    <li>Fragments have their own lifecycle, state, and back stack</li>
    <li>Fragments require API Level "Honeycomb" or greater</li>
  </ul>

  <h2>In this document</h2>
  <ol>
    <li><a href="#Design">Design Philosophy</a></li>
    <li><a href="#Creating">Creating a Fragment</a>
      <ol>
        <li><a href="#UI">Adding a user interface</a></li>
        <li><a href="#Adding">Adding a fragment to an activity</a></li>
      </ol>
    </li>
    <li><a href="#Managing">Managing Fragments</a></li>
    <li><a href="#Transactions">Performing Fragment Transactions</a></li>
    <li><a href="#CommunicatingWithActivity">Communicating with the Activity</a>
      <ol>
        <li><a href="#EventCallbacks">Creating event callbacks to the activity</a></li>
        <li><a href="#ActionBar">Adding items to the Action Bar</a></li>
      </ol>
    </li>
    <li><a href="#Lifecycle">Handling the Fragment Lifecycle</a>
      <ol>
        <li><a href="#CoordinadingWithActivity">Coordinating with the activity lifecycle</a></li>
      </ol>
    </li>
    <li><a href="#Example">Example</a></li>
  </ol>

  <h2>Key classes</h2>
  <ol>
    <li><code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code></li>
    <li><code><a href="../../../reference/android/app/FragmentManager.html">FragmentManager</a></code></li>
    <li><code><a href="../../../reference/android/app/FragmentTransaction.html">FragmentTransaction</a></code></li>
  </ol>

  <h2>Related samples</h2>
  <ol>
    <li><a
href="../../../resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#Fragment">ApiDemos</a></li>
  </ol>
</div>
</div>

<p>A <code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code> represents a behavior or a portion of user interface in an
<code><a href="../../../reference/android/app/Activity.html">Activity</a></code>. You can combine multiple fragments in a single activity to build a
multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a
modular section of an activity, which has its own lifecycle, receives its own input events, and
which you can add or remove while the activity is running.</p>
<p>Fragment是Activity中UI的一个行为或者一部分. 可以组合多个fragment放在一个单独的activity中来创建一个多界面区域的UI,并可以在多个activity里重用某一个fragment.你可以想象fragment是activity的一个模块化区域, 它有它自己的生命周期, 接收属于它的输入事件, 并且可以在activity运行期间添加和删除.</p>

<p>A fragment must always be embedded in an activity and the fragment's lifecycle is directly
affected by the host activity's lifecycle. For example, when the activity is paused, so are all
fragments in it, and when the activity is destroyed, so are all fragments. However, while an
activity is running (it is in the <em>resumed</em> <a
href="../../../guide/topics/fundamentals/activities.html#Lifecycle">lifecycle state</a>), you can
manipulate each fragment independently, such as add or remove them. When you perform such a
fragment transaction, you can also add it to a back stack that's managed by the
activity&mdash;each back stack entry in the activity is a record of the fragment transaction that
occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards),
by pressing the BACK key.</p>
<p>fragment通常被嵌入到activity中，它的生命周期直接影响activity的生命周期。比如，当一个activity被暂停，所有的包括在里面的fragment也会被暂停，如果activity被销毁，它们也一样被销毁。然而，当一个activity正在运行（resumed状态），你可以独立操作每一个fragment。比如添加或者删除它们。当你执行一个fragment事务，你可以把它添加到堆栈，并由一个activity管理--每一个activity中的堆栈实体都是一条fragment事务的记录。堆栈允许用户按back按钮恢复一个fragment事务。</p>

<p>When you add a fragment as a part of your activity layout, it lives in a <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> inside the activity's view hierarchy and defines its own layout of views.
You can insert a fragment into your activity layout by declaring the fragment in the activity's
layout file, as a <code>&lt;fragment&gt;</code> element, or from your application code by adding it to an
existing <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code>. However, a fragment is not required to be a part of the
activity layout; you may also use a fragment as an invisible worker for the activity.</p>
<p>当你添加一个fragment作为activity的一部分时，他存在于activity的view hierarchy中ViewGroup中，并且可以定义自己的布局。通过在activity的布局文件中定义fragment去添加一个fragment到你的activity中。通过<code>&lt;fragment&gt;</code>元素。然而，一个fragment不一定是activity布局的一部分。你可以使用一个fragment像后台工作者。</p>

<p>This document describes how to build your application to use fragments, including
how fragments can maintain their state when added to the activity's back stack, share
events with the activity and other fragments in the activity, contribute to the activity's action
bar, and more.</p>
<p>本文档描述了你怎么样建立application并使用fragment，包括当fragment添加到back stack后怎么保持他的状态，于其他activity或者fragment共享事件，帮助activity的活动条。</p>


<h2 id="Design">Design Philosophy 设计原理</h2>

<p>Android introduced fragments in Android 3.0 (API Level "Honeycomb"), primarily to support more
dynamic and flexible UI designs on large screens, such as tablets. Because a
tablet's screen is much larger than that of a mobile phone, there's more room to combine and
interchange UI components. Fragments allow such designs without the need for you to manage complex
changes to the view hierarchy. By dividing the layout of an activity into fragments, you become able
to modify the activity's appearance at runtime and preserve those changes in a back stack
that's managed by the activity.</p>
<p>Android在3.0引入fragment。主要为了支持大屏幕动态和灵活的UI设计。比如平板电脑。因为平板电脑的屏幕比手机大很多，有更多空间去存放UI组件。fragment的出现让你不用管理复杂的view hierarchy变化。通过划分布局给fragment，你可以在activity运行的时候修改它的表现，并且保存到activity管理的back stack里。</p>

<p>For example, a news application can use one fragment to show a list of articles on the
left and another fragment to display an article on the right&mdash;both fragments appear in one
activity, side by side, and each fragment has its own set of lifecycle callback methods and handle
their own user input events. Thus, instead of using one activity to select an article and another
activity to read the article, the user can select an article and read it all within the same
activity, as illustrated in figure 1.</p>
<p>例如，一个新的程序中你可以用一个fragment在左边显示文章标题列表，右边显示标题内容--两个fragment显示在一个activity中。每个fragment有自己的生命周期回调方法，并可以操作自己的用户输入事件。因此，以前的一个activity显示列表一个activity显示文章内容的形式可以变成一个activity实现。</p>

<img src="../../../images/fundamentals/fragments.png" alt="" />
<p class="img-caption"><strong>Figure 1.</strong> An example of how two UI modules that are
typically separated into two activities can be combined into one activity, using fragments.</p>


<p>A fragment should be a modular and reusable component in your application. That is, because the
fragment defines its own layout and its own behavior using its own lifecycle callbacks, you
can include one fragment in multiple activities. This is especially important because it allows you
to adapt your user experience to different screen sizes. For instance, you might include multiple
fragments in an activity only when the screen size is sufficiently large, and, when it is not,
launch separate activities that use different fragments.</p>
<p>一个fragment必须是一个模块和可以重复使用的组件。因为fragment定义了它自己的布局和行为。你可以包含一个fragment到多个activity中。这一点是非常重要的，因为它允许你把你的用户体验匹配到不同的屏幕尺寸中。不同的屏幕尺寸可以调用不同的包含fragment的activity。</p>

<p>For example&mdash;to continue with the news application example&mdash;the application can embed
two
fragments in <em>Activity A</em>, when running on an extra large screen (a tablet, for example).
However, on a normal-sized screen (a phone, for example),
there's not be enough room for both fragments, so <em>Activity A</em> includes only the fragment for
the list of articles, and when the user selects an article, it starts <em>Activity B</em>, which
includes the fragment to read the article. Thus, the application supports both design patterns
suggested in figure 1.</p>
<p>比如--继续前面那个例子--你可以嵌入2个fragment在<em>Activity A</em>中，当运行在一个特别大的屏幕中时（平板电脑）。可是，在一个普通尺寸的屏幕上（手机），没有足够的空间放2个fragment，因此用<em>Activity A</em>包含一个fragment存放文章列表，一个<em>Activity B</em>存放文章内容。</p>


<h2 id="Creating">Creating a Fragment 创建一个fragment</h2>

<div class="figure" style="width:314px">
<img src="../../../images/fragment_lifecycle.png" alt="" />
<p class="img-caption"><strong>Figure 2.</strong> The lifecycle of a fragment (while its
activity is running).</p>
</div>

<p>To create a fragment, you must create a subclass of <code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code> (or an existing
subclass of it). The <code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code> class has code that looks a lot like
an <code><a href="../../../reference/android/app/Activity.html">Activity</a></code>. It contains callback methods similar to an activity, such
as <code><a href="../../../reference/android/app/Fragment.html#onCreate(android.os.Bundle)">onCreate()</a></code>, <code><a href="../../../reference/android/app/Fragment.html#onStart()">onStart()</a></code>,
<code><a href="../../../reference/android/app/Fragment.html#onPause()">onPause()</a></code>, and <code><a href="../../../reference/android/app/Fragment.html#onStop()">onStop()</a></code>. In
fact, if you're converting an existing Android application to use fragments, you might simply move
code from your activity's callback methods into the respective callback methods of your
fragment.</p>
<p>创建一个fragment必须建立一个 <code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code>的子类。Fragment 类的代码看起来很像 Activity .它包含了和activity类似的回调方法, 例如 onCreate(), onStart(), onPause, 以及 onStop(). 事实上, 如果你准备将一个现成的Android应用转换到使用fragment, 你可能只需简单的将代码从你的activity的回调函数分别移动到你的fragment的回调方法.</p>

<p>Usually, you should implement at least the following lifecycle methods:</p>
<p>通常我们必须实现下面这些周期方法：</p>

<dl>
  <dt><code><a href="../../../reference/android/app/Fragment.html#onCreate(android.os.Bundle)">onCreate()</a></code></dt>
  <dd>The system calls this when creating the fragment. Within your implementation, you should
initialize essential components of the fragment that you want to retain when the fragment is
paused or stopped, then resumed.
<p>创建fragment的时候调用这个方法，在你的实现中，你必须初始化你想保留的fragment基本的组件，当暂停或者停止后能够恢复。</p></dd>
  <dt><code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code></dt>
  <dd>The system calls this when it's time for the fragment to draw its user interface for the
first time. To draw a UI for your fragment, you must return a <code><a href="../../../reference/android/view/View.html">View</a></code> from this
method that is the root of your fragment's layout. You can return null if the fragment does not
provide a UI.
<p>第一次绘制用户界面的时候会启动它。为了绘制一个界面，你必须在这个方法返回一个View，并做为fragment布局的主View，如果不提供UI的话也可以返回null。</p></dd>
  <dt><code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code></dt>
  <dd>The system calls this method as the first indication that the user is leaving the
fragment (though it does not always mean the fragment is being destroyed). This is usually where you
should commit any changes that should be persisted beyond the current user session (because
the user might not come back).
<p>用户离开这个fragment的时候调用这个方法作为第一个指示（离开并不一定是被销毁）。当用户离开当前会话的时候，你应该保存那些需要永久保存的数据（因为用户可能不会回来了）。</p></dd>
</dl>

<p>Most applications should implement at least these three methods for every fragment, but there are
several other callback methods you should also use to handle various stages of the
fragment lifecycle. All the lifecycle callback methods are discussed more later, in the section
about <a href="#Lifecycle">Handling the Fragment Lifecycle</a>.</p>
<p>其他的有关的方法在<a href="#Lifecycle">Handling the Fragment Lifecycle</a>中介绍</p>


<p>There are also a few subclasses that you might want to extend, instead of the base <code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code> class:</p>
<p>除了继承基本的Fragment类，你可能还需要继承下面这些子类。</p>

<dl>
  <dt><code><a href="../../../reference/android/app/DialogFragment.html">DialogFragment</a></code></dt>
  <dd>Displays a floating dialog. Using this class to create a dialog is a good alternative to using
the dialog helper methods in the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> class, because you can
incorporate a fragment dialog into the back stack of fragments managed by the activity,
allowing the user to return to a dismissed fragment.
<p>显示浮动的对话框。你可以把一个fragment对话框放入activity管理的fragment的back stack中，用户可以返回一个已经放弃的fragment。</p></dd>

  <dt><code><a href="../../../reference/android/app/ListFragment.html">ListFragment</a></code></dt>
  <dd>Displays a list of items that are managed by an adapter (such as a <code><a href="../../../reference/android/widget/SimpleCursorAdapter.html">SimpleCursorAdapter</a></code>), similar to <code><a href="../../../reference/android/app/ListActivity.html">ListActivity</a></code>. It provides
several methods for managing a list view, such as the <code><a href="../../../reference/android/app/ListFragment.html#onListItemClick(android.widget.ListView, android.view.View, int, long)">onListItemClick()</a></code> callback to
handle click events.
<p>显示一个列表。</p></dd>

  <dt><code><a href="../../../reference/android/preference/PreferenceFragment.html">PreferenceFragment</a></code></dt>
  <dd>Displays a hierarchy of <code><a href="../../../reference/android/preference/Preference.html">Preference</a></code> objects as a list, similar to
<code><a href="../../../reference/android/preference/PreferenceActivity.html">PreferenceActivity</a></code>. This is useful when creating a "settings"
activity for your application.<p>显示一个首选项，类似于“设置”这样的菜单。</p></dd>
</dl>


<h3 id="UI">Adding a user interface 添加一个UI</h3>

<p>A fragment is usually used as part of an activity's user interface and contributes its own
layout to the activity.</p>
<p>fragment通常是activity界面的一部分，并且提供自己的布局给activity。</p>

<p>To provide a layout for a fragment, you must implement the <code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code> callback method, which the Android system calls
when it's time for the fragment to draw its layout. Your implementation of this method must return a
<code><a href="../../../reference/android/view/View.html">View</a></code> that is the root of your fragment's layout.</p>
<p>为fragment提供布局你必须实现onCreateView()方法。你的方法要返回一个fragment布局的根View</p>

<p class="note"><strong>Note:</strong> If your fragment is a subclass of <code><a href="../../../reference/android/app/ListFragment.html">ListFragment</a></code>, the default implementation returns a <code><a href="../../../reference/android/widget/ListView.html">ListView</a></code> from
<code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code>, so you don't need to implement it.</p>
<p class="note"><strong>Note:</strong>如果是ListFragment的子类，默认返回的是ListView。</p>

<p>To return a layout from <code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code>, you can inflate it from a <a
href="../../../guide/topics/resources/layout-resource.html">layout resource</a> defined in XML. To
help you do so, <code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code> provides a
<code><a href="../../../reference/android/view/LayoutInflater.html">LayoutInflater</a></code> object.</p>
<p>从onCreateView()返回的View, 也可以从一个xml layout资源文件中读取并生成. 为了帮助你这么做, onCreateView() 提供了一个 LayoutInflater 对象.</p>

<p>For example, here's a subclass of <code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code> that loads a layout from the
<code>example_fragment.xml</code> file:</p>
<p>举个例子, 这里有一个Fragment的子类, 从文件 example_fragment.xml 加载了一个layout :</p>

<pre>
public static class ExampleFragment extends Fragment {
    &#64;Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}
</pre>

<div class="sidebox-wrapper">
<div class="sidebox">
  <h3>Creating a layout</h3>
  <p>In the sample above, <code>R.layout.example_fragment</code> is a reference to a layout resource
named <code>example_fragment.xml</code> saved in the application resources. For information about how to
create a layout in XML, see the <a href="../../../guide/topics/ui/index.html">User Interface</a>
documentation.</p>
</div>
</div>

<p>The <code>container</code> parameter passed to <code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code> is the parent <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> (from the activity's layout) in which
your fragment layout
will be inserted. The <code>savedInstanceState</code> parameter is a <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> that
provides data about the previous instance of the fragment, if the fragment is being resumed
(restoring state is discussed more in the section about <a href="#Lifecycle">Handling the
Fragment Lifecycle</a>).</p>
<p>传给onCreateView()的<code>container</code>参数是ViewGroup的实现，savedInstanceState 参数是一个 Bundle, 如果fragment是被恢复的,它提供关于fragment的之前的实例的数据</p>

<p>The <code><a href="../../../reference/android/view/LayoutInflater.html#inflate(int, android.view.ViewGroup, boolean)">inflate()</a></code> method takes
three arguments:</p>
<ul>
  <li>The resource ID of the layout you want to inflate. 资源ID</li>
  <li>The <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> to be the parent of the inflated layout. Passing the <code>container</code> is important in order for the system to apply layout parameters to the root view of the
inflated layout, specified by the parent view in which it's going.
<p>传入container是很重要的, 目的是为了让系统接受所要加载的layout的根view的layout参数,
由它将挂靠的父view指定. </p></li>
  <li>A boolean indicating whether the inflated layout should be attached to the <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> (the second parameter) during inflation. (In this case, this
is false because the system is already inserting the inflated layout into the <code>container</code>&mdash;passing true would create a redundant view group in the final layout.)
<p>布尔值指示在加载期间, 展开的layout是否应当附着到ViewGroup (第二个参数).
(在这个例子中, 指定了false, 因为系统已经把展开的layout插入到container – 传入true会在最后的layout中创建一个多余的view group.) </p></li>
</ul>

<p>Now you've seen how to create a fragment that provides a layout. Next, you need to add
the fragment to your activity.</p>



<h3 id="Adding">Adding a fragment to an activity 添加一个fragment到一个activity</h3>

<p>Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part
of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity
layout:</p>
<p>通常，一个fragment构建了主activity的一部分UI，它被作为activity整个层次结构的一部分插入。下面是添加的两个方法：</p>

<ul>
  <li><b>Declare the fragment inside the activity's layout file.</b><b>在activity布局文件中声明</b>
<p>In this case, you can
specify layout properties for the fragment as if it were a view. For example, here's the layout
file for an activity with two fragments:</p>
<p>下面是例子：</p>

<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"&gt;
    &lt;fragment android:name="com.example.news.ArticleListFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" /&gt;
    &lt;fragment android:name="com.example.news.ArticleReaderFragment"
            android:id="@+id/viewer"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="match_parent" /&gt;
&lt;/LinearLayout&gt;
</pre>
  <p>The <code>android:name</code> attribute in the <code>&lt;fragment&gt;</code> specifies the <code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code> class to instantiate in the layout.</p>
  <p><code>android:name</code>指定了实例化的Fragment类。</p>

<p>When the system creates this activity layout, it instantiates each fragment specified in the
layout and calls the <code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code> method for each one,
to retrieve each fragment's layout. The system inserts the <code><a href="../../../reference/android/view/View.html">View</a></code> returned by the
fragment directly in place of the <code>&lt;fragment&gt;</code> element.</p>
<p>当系统创建activity布局时，它实例化了布局文件中指定的每一个fragment，并为它们调用onCreateView()函数，以获取每一个fragment的布局。系统直接在<code>&lt;fragment&gt;</code>元素的位置插入fragment返回的View。</p>

<div class="note">
  <p><strong>Note:</strong> Each fragment requires a unique identifier that
the system can use to restore the fragment if the activity is restarted (and which you can use to
capture the fragment to perform transactions, such as remove it). There are three ways to provide an
ID for a fragment:</p>
<p><strong>Note:</strong>每个fragment都需要一个唯一的标识，如果重启activity，系统可用来恢复fragment（并且可用来捕捉fragment的事务处理，例如移除）。为fragment提供ID有三种方法:</p>
  <ul>
    <li>Supply the <code>android:id</code> attribute with a unique ID.  用android:id属性提供一个唯一的标识。</li>
    <li>Supply the <code>android:tag</code> attribute with a unique string.   用android:tag属性提供一个唯一的字符串。</li>
    <li>If you provide neither of the previous two, the system uses the ID of the container 
view.  如果上述两个属性都没有，系统会使用其容器视图（view）的ID。</li>
  </ul>
</div>
  </li>

  <li><b>Or, programmatically add the fragment to an existing <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code>.  或者，通过编码将fragment添加到已存在的ViewGroup中。</b>
<p>At any time while your activity is running, you can add fragments to your activity layout. You
simply need to specify a <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> in which to place the fragment.</p>
<p>在activity运行的任何时候，你都可以将fragment添加到activity布局中。你仅需要简单指定用来放置fragment的ViewGroup。</p>

  <p>To make fragment transactions in your activity (such as add, remove, or replace a
fragment), you must use APIs from <code><a href="../../../reference/android/app/FragmentTransaction.html">FragmentTransaction</a></code>. You can get an instance
of <code><a href="../../../reference/android/app/FragmentTransaction.html">FragmentTransaction</a></code> from your <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> like this:</p>
<p>你应当使用FragmentTransaction的API来对activity中的fragment进行操作（例如添加，移除，或者替换fragment）。你可以像下面这样从Activity中取得FragmentTransaction的实例:</p>

<pre>
FragmentManager fragmentManager = <code><a href="../../../reference/android/app/Activity.html#getFragmentManager()">getFragmentManager()</a></code>
FragmentTransaction fragmentTransaction = fragmentManager.<code><a href="../../../reference/android/app/FragmentManager.html#beginTransaction()">beginTransaction()</a></code>;
</pre>

<p>You can then add a fragment using the <code><a href="../../../reference/android/app/FragmentTransaction.html#add(int, android.app.Fragment)">add()</a></code> method, specifying the fragment to add and
the view in which to insert it. For example:</p>
<p>可以用add()函数添加fragment，并指定要添加的fragment以及要将其插入到哪个视图（view）之中：</p>

<pre>
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
</pre>

  <p>The first argument passed to <code><a href="../../../reference/android/app/FragmentTransaction.html#add(int, android.app.Fragment)">add()</a></code>
is the <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> in which the fragment should be placed, specified by
resource ID, and the second parameter is the fragment to add.</p>
<p>传入add()函数的第一个参数是fragment被放置的ViewGroup，它由资源ID（resource ID）指定，第二个参数就是要添加的fragment。</p>
  <p>Once you've made your changes with
<code><a href="../../../reference/android/app/FragmentTransaction.html">FragmentTransaction</a></code>, you must
call <code><a href="../../../reference/android/app/FragmentTransaction.html#commit()">commit()</a></code> for the changes to take effect.</p>
<p>一旦通过FragmentTransaction 做了更改，都应当使用commit()使变化生效。</p>
  </li>
</ul>


<h4 id="AddingWithoutUI">Adding a fragment without a UI 添加无界面的fragment</h4>

<p>The examples above show how to add a fragment to your activity in order to provide a UI. However,
you can also use a fragment to provide a background behavior for the activity without presenting
additional UI.</p>
<p>上面的例子是如何将fragment添加到activity中去，目的是提供一个用户界面。然而，也可以使用fragment为activity提供后台动作，却不呈现多余的用户界面。</p>

<p>To add a fragment without a UI, add the fragment from the activity using <code><a href="../../../reference/android/app/FragmentTransaction.html#add(android.app.Fragment, java.lang.String)">add(Fragment, String)</a></code> (supplying a unique string "tag" for the
fragment, rather than a view ID). This adds the fragment, but, because it's not associated with a
view in the activity layout, it does not receive a call to <code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code>. So you don't need to implement that method.</p>
<p>想要添加没有界面的fragment ，可以使用add(Fragment, String)（为fragment提供一个唯一的字符串“tag”，而不是视图（view）ID）。这样添加了fragment，但是，因为还没有关联到activity布局中的视图（view） ，收不到onCreateView()的调用。所以不需要实现这个方法。</p>

<p>Supplying a string tag for the fragment isn't strictly for non-UI fragments&mdash;you can also
supply string tags to fragments that do have a UI&mdash;but if the fragment does not have a
UI, then the string tag is the only way to identify it. If you want to get the fragment from the
activity later, you need to use <code><a href="../../../reference/android/app/FragmentManager.html#findFragmentByTag(java.lang.String)">findFragmentByTag()</a></code>.</p>
<p>为无界面fragment提供字符串标签并不是专门针对无界面fragment的——也可以为有界面fragment提供字符串标签——但是对于无界面fragment，字符串标签是唯一识别它的方法。如果之后想从activity中取到fragment，需要使用findFragmentByTag()。</p>

<p>For an example activity that uses a fragment as a background worker, without a UI, see the <a
href="../../../resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentRetainInstance.html"><code>FragmentRetainInstance.java</code></a> sample.</p>



<h2 id="Managing">Managing Fragments 管理fragment</h2>

<p>To manage the fragments in your activity, you need to use <code><a href="../../../reference/android/app/FragmentManager.html">FragmentManager</a></code>. To
get it, call <code><a href="../../../reference/android/app/Activity.html#getFragmentManager()">getFragmentManager()</a></code> from your activity.</p>
<p>想要管理activity中的fragment，可以使用FragmentManager。可以通过在activity中调用getFragmentManager()获得。</p>

<p>Some things that you can do with <code><a href="../../../reference/android/app/FragmentManager.html">FragmentManager</a></code> include:</p>
<p>使用FragmentManager 可以做如下事情，包括：</p>

<ul>
  <li>Get fragments that exist in the activity, with <code><a href="../../../reference/android/app/FragmentManager.html#findFragmentById(int)">findFragmentById()</a></code> (for fragments that provide a UI in
the activity layout) or <code><a href="../../../reference/android/app/FragmentManager.html#findFragmentByTag(java.lang.String)">findFragmentByTag()</a></code> (for fragments that do or don't provide a UI).
<p>使用findFragmentById()（用于在activity布局中提供有界面的fragment）或者findFragmentByTag()获取activity中存在的fragment（用于有界面或者没有界面的fragment）。</p></li> 
  <li>Pop fragments off the back stack, with <code><a href="../../../reference/android/app/FragmentManager.html#popBackStack()">popBackStack()</a></code> (simulating a BACK command by the user).
  <p>使用popBackStack()（模仿用户的BACK命令）从后台栈弹出fragment。</p></li>
  <li>Register a listener for changes to the back stack, with <code><a href="../../../reference/android/app/FragmentManager.html#addOnBackStackChangedListener(android.app.FragmentManager.OnBackStackChangedListener)">addOnBackStackChangedListener()</a></code>.
  <p>使用addOnBackStackChangedListener()注册一个监听后台栈变化的监听器。</p></li>
</ul>

<p>For more information about these methods and others, refer to the <code><a href="../../../reference/android/app/FragmentManager.html">FragmentManager</a></code> class documentation.</p>

<p>As demonstrated in the previous section, you can also use <code><a href="../../../reference/android/app/FragmentManager.html">FragmentManager</a></code>
to open a <code><a href="../../../reference/android/app/FragmentTransaction.html">FragmentTransaction</a></code>, which allows you to perform transactions, such as
add and remove fragments.</p>


<h2 id="Transactions">Performing Fragment Transactions 处理fragment事务</h2>

<p>A great feature about using fragments in your activity is the ability to add, remove, replace,
and perform other actions with them, in response to user interaction. Each set of changes that you
commit to the activity is called a transaction and you can perform one using APIs in <code><a href="../../../reference/android/app/FragmentTransaction.html">FragmentTransaction</a></code>. You can also save each transaction to a back stack managed by the
activity, allowing the user to navigate backward through the fragment changes (similar to navigating
backward through activities).</p>
<p>在activity中使用fragment的一大特点是具有添加、删除、替换，和执行其它动作的能力，以响应用户的互动。提交给activity的每一系列变化被称为事务，并且可以用FragmentTransaction 中的APIs处理。你也可以将每一个事务保存在由activity管理的后台栈中，并且允许用户导航回退fragment变更（类似于activity的导航回退）。</p>

<p>You can acquire an instance of <code><a href="../../../reference/android/app/FragmentTransaction.html">FragmentTransaction</a></code> from the <code><a href="../../../reference/android/app/FragmentManager.html">FragmentManager</a></code> like this:</p>

<pre>
FragmentManager fragmentManager = <code><a href="../../../reference/android/app/Activity.html#getFragmentManager()">getFragmentManager()</a></code>;
FragmentTransaction fragmentTransaction = fragmentManager.<code><a href="../../../reference/android/app/FragmentManager.html#beginTransaction()">beginTransaction()</a></code>;
</pre>

<p>Each transaction is a set of changes that you want to perform at the same time. You can set
up all the changes you want to perform for a given transaction using methods such as <code><a href="../../../reference/android/app/FragmentTransaction.html#add(android.app.Fragment, java.lang.String)">add()</a></code>, <code><a href="../../../reference/android/app/FragmentTransaction.html#remove(android.app.Fragment)">remove()</a></code>,
and <code><a href="../../../reference/android/app/FragmentTransaction.html#replace(int, android.app.Fragment)">replace()</a></code>. Then, to apply the transaction
to the activity, you must call <code><a href="../../../reference/android/app/FragmentTransaction.html#commit()">commit()</a></code>.</p>
<p>每项事务是在同一时间内要执行的一系列的变更。你可以为一个给定的事务用相关方法设置想要执行的所有变化，例如add()，remove()，和replace()。然后，用commit()将事务提交给activity。</p>
</dl>

<p>Before you call <code><a href="../../../reference/android/app/FragmentTransaction.html#commit()">commit()</a></code>, however, you might want to call <code><a href="../../../reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)">addToBackStack()</a></code>, in order to add the transaction
to a back stack of fragment transactions. This back stack is managed by the activity and allows
the user to return to the previous fragment state, by pressing the BACK key.</p>
<p>然而，在调用commit()之前，为了将事务添加到fragment事务后台栈中，你可能会想调用addToBackStatck()。这个后台栈由activity管理，并且允许用户通过按BACK键回退到前一个fragment状态。</p>

<p>For example, here's how you can replace one fragment with another, and preserve the previous
state in the back stack:</p>
<p>举个例子，下面的代码是如何使用另一个fragment代替一个fragment，并且将之前的状态保留在后台栈中：</p>

<pre>
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();
</pre>

<p>In this example, <code>newFragment</code> replaces whatever fragment (if any) is currently in the
layout container identified by the <code>R.id.fragment_container</code> ID. By calling <code><a href="../../../reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)">addToBackStack()</a></code>, the replace transaction is
saved to the back stack so the user can reverse the transaction and bring back the
previous fragment by pressing the BACK key.</p>
<p>在这个例子中，newFragment替换了当前在布局容器中用R.id.fragment_container标识的所有的fragment（如果有的话），替代的事务被保存在后台栈中，因此用户可以回退该事务，可通过按BACK键还原之前的fragment。</p>

<p>If you add multiple changes to the transaction (such as another <code><a href="../../../reference/android/app/FragmentTransaction.html#add(android.app.Fragment, java.lang.String)">add()</a></code> or <code><a href="../../../reference/android/app/FragmentTransaction.html#remove(android.app.Fragment)">remove()</a></code>) and call <code><a href="../../../reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)">addToBackStack()</a></code>, then all changes applied
before you call <code><a href="../../../reference/android/app/FragmentTransaction.html#commit()">commit()</a></code> are added to the
back stack as a single transaction and the BACK key will reverse them all together.</p>
<p>如果添加多个变更事务（例如另一个add()或者remove()）并调用addToBackStack()，那么在调用commit()之前的所有应用的变更被作为一个单独的事务添加到后台栈中，并且BACK键可以将它们一起回退。</p>

<p>The order in which you add changes to a <code><a href="../../../reference/android/app/FragmentTransaction.html">FragmentTransaction</a></code> doesn't matter,
except:</p>
<p>将变更添加到FragmentTransaction中的顺序注意以下两点：</p>
<ul>
  <li>You must call <code><a href="../../../reference/android/app/FragmentTransaction.html#commit()">commit()</a></code> last
  <p>你必须最后调用commit()</p></li>
  <li>If you're adding multiple fragments to the same container, then the order in which
you add them determines the order they appear in the view hierarchy
<p>如果你正将多个fragment添加到同一个容器中，那么添加顺序决定了它们在视图层次（view hierarchy）里显示的顺序。</p></li>
</ul>

<p>If you do not call <code><a href="../../../reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)">addToBackStack()</a></code> when you perform a transaction that removes a fragment, then that fragment is
destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you
do call <code><a href="../../../reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)">addToBackStack()</a></code> when
removing a fragment, then the fragment is <em>stopped</em> and will be resumed if the user navigates
back.</p>
<p>在执行删除fragment事务时，如果没有调用addToBackStack()，那么事务一提交fragment就会被销毁，而且用户也无法回退它。然而，当移除一个fragment时，如果调用了addToBackStack()，那么之后fragment会被停止，如果用户回退，它将被恢复过来。</p>

<p class="note"><strong>Tip:</strong> For each fragment transaction, you can apply a transition
animation, by calling <code><a href="../../../reference/android/app/FragmentTransaction.html#setTransition(int)">setTransition()</a></code> before
you commit.</p>
<p class="note"><strong>Tip:</strong> 对于每一个fragment事务，在提交之前通过调用setTransition()来应用一系列事务动作。</p>

<p>Calling <code><a href="../../../reference/android/app/FragmentTransaction.html#commit()">commit()</a></code> does not perform the transaction
immediately. Rather, it schedules it to run on the activity's UI thread (the "main" thread) as soon
as the thread is able to do so. If necessary, however, you may call <code><a href="../../../reference/android/app/FragmentManager.html#executePendingTransactions()">executePendingTransactions()</a></code> from your UI thread to immediately execute
transactions submitted by <code><a href="../../../reference/android/app/FragmentTransaction.html#commit()">commit()</a></code>. Doing so is
usually not necessary unless the transaction is a dependency for jobs in other threads.</p>
<p>调用commit()并不立刻执行事务，相反，而是采取预约方式，一旦activity的界面线程（主线程）准备好便可运行起来。然而，如果有必要的话，你可以从界面线程调用executePendingTransations()立即执行由commit()提交的事务。但这样做，通常是没有必要的，除非其它线程的工作依赖与该项事务。</p>

<p class="caution"><strong>Caution:</strong> You can commit a transaction using <code><a href="../../../reference/android/app/FragmentTransaction.html#commit()">commit()</a></code> only prior to the activity <a
href="../../../guide/topics/fundamentals/activities.html#SavingActivityState">saving its
state</a> (when the user leaves the activity). If you attempt to commit after that point, an
exception will be thrown. This is because the state after the commit can be lost if the activity
needs to be restored. For situations in which its okay that you lose the commit, use <code><a href="../../../reference/android/app/FragmentTransaction.html#commitAllowingStateLoss()">commitAllowingStateLoss()</a></code>.</p>
<p>警告：只能在activity保存状态（当用户离开activity时）之前用commit()提交事务。如果你尝试在那时之后提交，会抛出一个异常。这是因为如果activity需要被恢复，提交后的状态会被丢失。对于这类丢失提交的情况，可使用commitAllowingStateLoss()</p>



<h2 id="CommunicatingWithActivity">Communicating with the Activity 与activity通讯</h2>

<p>Although a <code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code> is implemented as an object that's independent from an
<code><a href="../../../reference/android/app/Activity.html">Activity</a></code> and can be used inside multiple activities, a given instance of
a fragment is directly tied to the activity that contains it.</p>
<p>尽管Fragment被实现为一个对象，它独立于Activity并可以在多个Activity中使用，一个给定的fragment实例直接被捆绑在包含它的Activity中。
</p>

<p>Specifically, the fragment can access the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> instance with <code><a href="../../../reference/android/app/Fragment.html#getActivity()">getActivity()</a></code> and easily perform tasks such as find a view in the
activity layout:</p>
<p>特别是，fragment可以通过getActivity()函数访问Activity，并且很容易的执行类似于查找activity布局中的视图的任务：</p>

<pre>
View listView = <code><a href="../../../reference/android/app/Fragment.html#getActivity()">getActivity()</a></code>.<code><a href="../../../reference/android/app/Activity.html#findViewById(int)">findViewById</a></code>(R.id.list);
</pre>

<p>Likewise, your activity can call methods in the fragment by acquiring a reference to the
<code><a href="../../../reference/android/app/Fragment.html">Fragment</a></code> from <code><a href="../../../reference/android/app/FragmentManager.html">FragmentManager</a></code>, using <code><a href="../../../reference/android/app/FragmentManager.html#findFragmentById(int)">findFragmentById()</a></code> or <code><a href="../../../reference/android/app/FragmentManager.html#findFragmentByTag(java.lang.String)">findFragmentByTag()</a></code>. For example:</p>
<p>同样的，activity能够调用fragment的函数findFragmentById()或者findFragmentByTag()，从FragmentManager中获取Fragment的索引，例如：</p>

<pre>
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
</pre>


<h3 id="EventCallbacks">Creating event callbacks to the activity 为activity创建事件回调函数</h3>

<p>In some cases, you might need a fragment to share events with the activity. A good way to do that
is to define a callback interface inside the fragment and require that the host activity implement
it. When the activity receives a callback through the interface, it can share the information with
other fragments in the layout as necessary.</p>
<p>在一些情况下，你可能需要fragment与activity共享事件。这样做的一个好方法是在fragment内部定义一个回调接口，并需要宿主activity实现它。当activity通过接口接收到回调时，可以在必要时与布局中的其它fragment共享信息。</p>

<p>For example, if a news application has two fragments in an activity&mdash;one to show a list of
articles (fragment A) and another to display an article (fragment B)&mdash;then fragment A must tell
the activity when a list item is selected so that it can tell fragment B to display the article. In
this case, the <code>OnArticleSelectedListener</code> interface is declared inside fragment A:</p>
<p>举个例子，如果新闻应用的actvity中有两个fragment——一个显示文章列表（fragment A），另一个显示一篇文章（fragment B）——然后fragment A 必须要告诉activity列表项何时被选中，这样，activity可以通知fragment B显示这篇文章。这种情况下，在fragment A内部声明接口OnArticleSelectedListener：</p>

<pre>
public static class FragmentA extends ListFragment {
    ...
    // Container Activity must implement this interface
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }
    ...
}
</pre>

<p>Then the activity that hosts the fragment implements the <code>OnArticleSelectedListener</code>
interface and
overrides <code>onArticleSelected()</code> to notify fragment B of the event from fragment A. To ensure
that the host activity implements this interface, fragment A's <code><a href="../../../reference/android/app/Fragment.html#onAttach(android.app.Activity)">onAttach()</a></code> callback method (which the system calls when adding
the fragment to the activity) instantiates an instance of <code>OnArticleSelectedListener</code> by
casting the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> that is passed into <code><a href="../../../reference/android/app/Fragment.html#onAttach(android.app.Activity)">onAttach()</a></code>:</p>
<p>然后fragment的宿主activity实现了OnArticleSelectedListener接口，并且重写onArticleSelected()以通知fragment B来自于fragment A的事件。为了确保宿主activity实现了这个接口，fragment A的onAttach()回调函数（当添加fragment到activity中时系统会调用它）通过作为参数传入onAttach()的activity的类型转换来实例化一个OnArticleSelectedListener实例。</p>

<pre>
public static class FragmentA extends ListFragment {
    OnArticleSelectedListener mListener;
    ...
    &#64;Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
        }
    }
    ...
}
</pre>

<p>If the activity has not implemented the interface, then the fragment throws a
<code><a href="../../../reference/java/lang/ClassCastException.html">ClassCastException</a></code>.
On success, the <code>mListener</code> member holds a reference to activity's implementation of 
<code>OnArticleSelectedListener</code>, so that fragment A can share events with the activity by calling
methods defined by the <code>OnArticleSelectedListener</code> interface. For example, if fragment A is an
extension of <code><a href="../../../reference/android/app/ListFragment.html">ListFragment</a></code>, each time
the user clicks a list item, the system calls <code><a href="../../../reference/android/app/ListFragment.html#onListItemClick(android.widget.ListView, android.view.View, int, long)">onListItemClick()</a></code> in the fragment, which then calls <code>onArticleSelected()</code> to share
the event with the activity:</p>
<p>如果activity没有实现这个接口，那么fragment会抛出一个ClassCaseException异常。一旦成功，mListener成员会保留一个activity的OnArticleSelectedListener实现的引用，由此fragment A可以通过调用由OnArticleSelectedListener接口定义的方法与activity共享事件。例如，如果fragment A是ListFragment的子类，每次用户点击列表项时，系统都会调用fragment的onListItemClick()事件，然后fragment调用onArticleSelected()来与activity共享事件。</p>

<pre>
public static class FragmentA extends ListFragment {
    OnArticleSelectedListener mListener;
    ...
    &#64;Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Append the clicked item's row ID with the content provider Uri
        Uri noteUri = ContentUris.<code><a href="../../../reference/android/content/ContentUris.html#withAppendedId(android.net.Uri, long)">withAppendedId</a></code>(ArticleColumns.CONTENT_URI, id);
        // Send the event and Uri to the host activity
        mListener.onArticleSelected(noteUri);
    }
    ...
}
</pre>

<p>The <code>id</code> parameter passed to <code><a href="../../../reference/android/app/ListFragment.html#onListItemClick(android.widget.ListView, android.view.View, int, long)">onListItemClick()</a></code> is the row ID of the clicked item,
which the activity (or other fragment) uses to fetch the article from the application's <code><a href="../../../reference/android/content/ContentProvider.html">ContentProvider</a></code>.</p>
<p>传递给onListItemClick()的参数id是点击的列表项行id，activity（或者其它fragment）用以从应用的ContentProvider获取文章。</p>

<p><!--To see a complete implementation of this kind of callback interface, see the <a
href="../../../resources/samples/NotePad/index.html">NotePad sample</a>. -->More information about
using a content provider is available in the <a
href="../../../guide/topics/providers/content-providers.html">Content Providers</a> document.</p>



<h3 id="ActionBar">Adding items to the Action Bar 添加项目到Action Bar</h3>

<p>Your fragments can contribute menu items to the activity's <a
href="../../../guide/topics/ui/menus.html#options-menu">Options Menu</a> (and, consequently, the <a
href="../../../guide/topics/ui/actionbar.html">Action Bar</a>) by implementing
<code><a href="../../../reference/android/app/Fragment.html#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)">onCreateOptionsMenu()</a></code>. In order
for this method to receive calls, however, you must call <code><a href="../../../reference/android/app/Fragment.html#setHasOptionsMenu(boolean)">setHasOptionsMenu()</a></code> during <code><a href="../../../reference/android/app/Fragment.html#onCreate(android.os.Bundle)">onCreate()</a></code>, to indicate that the fragment
would like to add items to the Options Menu (otherwise, the fragment will not receive a call to
<code><a href="../../../reference/android/app/Fragment.html#onCreateOptionsMenu(android.view.Menu, android.view.MenuInflater)">onCreateOptionsMenu()</a></code>).</p>
<p>你的fragments可以通过实现onCreateOptionsMenu()来构建菜单项到activity的Options Menu（因此Action Bar也一样）。为了使用这个方法接收到调用，不管怎样，你必须在onCreate()期间调用setHasOptionsMenu()，来指明想要添加项目到Options Menu的那个fragment（否则，fragment将接收不到onCreateOptionsMenu()的调用）。</p>

<p>Any items that you then add to the Options Menu from the fragment are appended to the existing
menu items. The fragment also receives callbacks to <code><a href="../../../reference/android/app/Fragment.html#onOptionsItemSelected(android.view.MenuItem)">onOptionsItemSelected()</a></code> when a menu item
is selected.</p>
<p>任何想要在fragment中的Options Menu添加的项目都追加到已有的菜单项后面。当菜单项被选中时，fragment也会接收到对onOptionsItemSelected()的回调。</p>

<p>You can also register a view in your fragment layout to provide a context menu by calling <code><a href="../../../reference/android/app/Fragment.html#registerForContextMenu(android.view.View)">registerForContextMenu()</a></code>. When the user opens
the context menu, the fragment receives a call to <code><a href="../../../reference/android/app/Fragment.html#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)">onCreateContextMenu()</a></code>. When the user selects an item, the fragment receives a call to <code><a href="../../../reference/android/app/Fragment.html#onContextItemSelected(android.view.MenuItem)">onContextItemSelected()</a></code>.</p>
<p>你也可以通过调用registerForContextMenu()在fragment布局中注册一个view以提供一个context menu。当用户打开context menu时，fragment接收到对onCreateContextMenu()的回调。当用户选中一个项目时，fragment接收到对onContextItemSelected()的回调。</p>

<p class="note"><strong>Note:</strong> Although your fragment receives an on-item-selected callback
for each menu item it adds, the activity is first to receive the respective callback when the user
selects a menu item. If the activity's implementation of the on-item-selected callback does not
handle the selected item, then the event is passed to the fragment's callback. This is true for
the Options Menu and context menus.</p>
<p>注意：尽管你的fragment会接收到为添加到每个菜单项被选择菜单项的回调，但当用户选择一个菜单项时，activity会首先接收到对应的回调。如果activity的选择菜单项回调的实现没有处理被选中的项目，那么该事件被传递给fragment的回调。这同样适用于Options Menu和context menu。</p>

<p>For more information about menus, see the <a
href="../../../guide/topics/ui/menus.html">Menus</a> and <a
href="../../../guide/topics/ui/actionbar.html">Action Bar</a> developer guides.</p>




<h2 id="Lifecycle">Handling the Fragment Lifecycle 操作fragment生命周期</h2>

<div class="figure" style="width:403px">
<img src="../../../images/activity_fragment_lifecycle.png" alt=""/>
<p class="img-caption"><strong>Figure 3.</strong> The activity lifecycle's affect on the fragment
lifecycle.</p>
</div>

<p>Managing the lifecycle of a fragment is a lot like managing the lifecycle of an activity. Like
an activity, a fragment can exist in three states:</p>
<p>管理fragment生命周期与管理activity生命周期很相像。像activity一样，fragment也有三种状态：</p>

<dl>
  <dt><i>Resumed</i></dt>
    <dd>The fragment is visible in the running activity.  fragment在运行中的activity可见。 </dd>

  <dt><i>Paused</i></dt>
    <dd>Another activity is in the foreground and has focus, but the activity in which this
fragment lives is still visible (the foreground activity is partially transparent or doesn't
cover the entire screen).
<p>另一个activity处于前台且得到焦点，但是这个fragment所在的activity仍然可见（前台activity部分透明，或者没有覆盖全屏）。 </p></dd>

  <dt><i>Stopped</i></dt>
    <dd>The fragment is not visible. Either the host activity has been stopped or the
fragment has been removed from the activity but added to the back stack. A stopped fragment is
still alive (all state and member information is retained by the system). However, it is no longer
visible to the user and will be killed if the activity is killed.
<p>fragment不可见。要么宿主activity已经停止，要么fragment已经从activity上移除，但已被添加到后台栈中。一个停止的fragment仍然活着（所有状态和成员信息仍然由系统保留着）。但是，它对用户来讲已经不再可见，并且如果activity被杀掉，它也将被杀掉。 </p></dd>
</dl>

<p>Also like an activity, you can retain the state of a fragment using a <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code>, in case the activity's process is killed and you need to restore the
fragment state when the activity is recreated. You can save the state during the fragment's <code><a href="../../../reference/android/app/Fragment.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code> callback and restore it during
either <code><a href="../../../reference/android/app/Fragment.html#onCreate(android.os.Bundle)">onCreate()</a></code>, <code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code>, or <code><a href="../../../reference/android/app/Fragment.html#onActivityCreated(android.os.Bundle)">onActivityCreated()</a></code>. For more information about saving
state, see the <a
href="../../../guide/topics/fundamentals/activities.html#SavingActivityState">Activities</a>
document.</p>
<p>同activity类似的还有，你也可以用Bundle保存fragment状态，万一activity的进程被杀掉了，并且在activity被重新创建时，你需要恢复fragment状态。在回调执行fragment的onSaveInstanceState()期间可以保存状态，在onCreate()，onCreateView()，或者onActvityCreate()中可以恢复状态。更多关于保存状态的信息，参考Activities文档。</p>

<p>The most significant difference in lifecycle between an activity and a fragment is how one is
stored in its respective back stack. An activity is placed into a back stack of activities
that's managed by the system when it's stopped, by default (so that the user can navigate back
to it with the BACK key, as discussed in <a
href="../../../guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>).
However, a fragment is placed into a back stack managed by the host activity only when you
explicitly request that the instance be saved by calling <code><a href="../../../reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)">addToBackStack()</a></code> during a transaction that
removes the fragment.</p>
<p>在生命周期方面,activity与fragment之间一个很重要的不同，就是在各自的后台栈中是如何存储的。当activity停止时，默认情况下，activity被安置在由系统管理的activity后台栈中（因此用户可以按BACK键回退导航，就像在Tasks和后台栈中讨论的那样）。但是，仅当你在一个事务被移除时，通过显式调用addToBackStack()请求保存的实例，该fragment才被置于由宿主activity管理的后台栈。</p>

<p>Otherwise, managing the fragment lifecycle is very similar to managing the activity
lifecycle. So, the same practices for <a
href="../../../guide/topics/fundamentals/activities.html#Lifecycle">managing the activity
lifecycle</a> also apply to fragments. What you also need to understand, though, is how the life
of the activity affects the life of the fragment.</p>
<p>除此之外，管理fragment的生命周期与管理activity的生命周期非常相似。所以，管理activity生命周期的实践同样也适用于fragment。你需要了解的，仅仅是activity的生命周期如何影响fragment的的。</p>


<h3 id="CoordinatingWithActivity">Coordinating with the activity lifecycle 与activity生命周期协作</h3>

<p>The lifecycle of the activity in which the fragment lives directly affects the lifecycle of the
fragment, such that each lifecycle callback for the activity results in a similar callback for each
fragment. For example, when the activity receives <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code>, each
fragment in the activity receives <code><a href="../../../reference/android/app/Fragment.html#onPause()">onPause()</a></code>.</p>
<p>fragment所生存的activity生命周期直接影响着fragment的生命周期，由此针对activity的每一个生命周期回调都会引发一个fragment类似的回调。例如，当activity接收到onPause()时，这个activity之中的每个fragment都会接收到onPause()。</p>

<p>Fragments have a few extra lifecycle callbacks, however, that handle unique interaction with the
activity in order to perform actions such as build and destroy the fragment's UI. These additional
callback methods are:</p>
<p>Fragment有一些额外的生命周期回调方法，然而，为了处理像是创建和销毁fragment界面，它与activity进行独特的交互。这些额外的回调方法是：</p>

<dl>
  <dt><code><a href="../../../reference/android/app/Fragment.html#onAttach(android.app.Activity)">onAttach()</a></code></dt>
    <dd>Called when the fragment has been associated with the activity (the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> is passed in here).
	<p>当fragment被绑定到activity时调用（Activity会被传入）。</p></dd>
  <dt><code><a href="../../../reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView()</a></code></dt>
    <dd>Called to create the view hierarchy associated with the fragment.
	<p>创建与fragment相关的视图体系时被调用。</p></dd>
  <dt><code><a href="../../../reference/android/app/Fragment.html#onActivityCreated(android.os.Bundle)">onActivityCreated()</a></code></dt>
    <dd>Called when the activity's <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code> method has returned.
	<p>当activity的onCreate()函数返回时被调用。 </p></dd>
  <dt><code><a href="../../../reference/android/app/Fragment.html#onDestroyView()">onDestroyView()</a></code></dt>
    <dd>Called when the view hierarchy associated with the fragment is being removed.
	<p>当与fragment关联的视图体系正被移除时被调用。</p></dd>
  <dt><code><a href="../../../reference/android/app/Fragment.html#onDetach()">onDetach()</a></code></dt>
    <dd>Called when the fragment is being disassociated from the activity.
	<p>当fragment正与activity解除关联时被调用。</p></dd>
</dl>

<p>The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated
by figure 3. In this figure, you can see how each successive state of the activity determines which
callback methods a fragment may receive. For example, when the activity has received its <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code> callback, a fragment in the activity receives no more than
the <code><a href="../../../reference/android/app/Fragment.html#onActivityCreated(android.os.Bundle)">onActivityCreated()</a></code> callback.</p>
<p>fragment的生命周期流程实际上是受其宿主activity影响，如图3所示。在这张图中，可以看到activity的每个连续状态是如何决定fragment可能接收到哪个回调函数的。例如，当activity接收到它的onCreate()回调时，activity之中的fragment接收到的仅仅是onActivityCreated()回调。 </p>

<p>Once the activity reaches the resumed state, you can freely add and remove fragments to the
activity. Thus, only while the activity is in the resumed state can the lifecycle of a fragment
change independently.</p>
<p>一旦activity处于resumed状态，则可以在activity中自由的添加或者移除fragment。因此，只有当activity处于resumed状态时，fragment的生命周期才可以独立变化。</p>

<p>However, when the activity leaves the resumed state, the fragment again is pushed through its
lifecycle by the activity.</p>
<p>然而，当activity离开恢复状态时，fragment再一次被activity推入它的生命周期中。</p>




<h2 id="Example">Example</h2>

<p>To bring everything discussed in this document together, here's an example of an activity
using two fragments to create a two-pane layout. The activity below includes one fragment to
show a list of Shakespeare play titles and another to show a summary of the play when selected
from the list. It also demonstrates how to provide different configurations of the fragments,
based on the screen configuration.</p>

<p class="note"><strong>Note:</strong> The complete source code for this activity is available in
<a
href="../../../resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentLayout.html"><code>FragmentLayout.java</code></a>.</p>

<p>The main activity applies a layout in the usual way, during <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code>:</p>

<pre>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_layout);
}</pre>

<p>The layout applied is <code>fragment_layout.xml</code>:</p>

<pre>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent"&gt;

    &lt;fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
            android:id="@+id/titles" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent" /&gt;

    &lt;FrameLayout android:id="@+id/details" android:layout_weight="1"
            android:layout_width="0px" android:layout_height="match_parent"
            android:background="?android:attr/detailsElementBackground" /&gt;

&lt;/LinearLayout&gt;</pre>

<p>Using this layout, the system instantiates the <code>TitlesFragment</code> (which lists the play
titles) as soon as the activity loads the layout, while the <code><a href="../../../reference/android/widget/FrameLayout.html">FrameLayout</a></code>
(where the fragment for showing the play summary will go) consumes space on the right side of the
screen, but remains empty at first. As you'll see below, it's not until the user selects an item
from the list that a fragment is placed into the <code><a href="../../../reference/android/widget/FrameLayout.html">FrameLayout</a></code>.</p>

<p>However, not all screen configurations are wide enough to show both the list of
plays and the summary, side by side. So, the layout above is used only for the landscape
screen configuration, by saving it at <code>res/layout-land/fragment_layout.xml</code>.</p>

<p>Thus, when the screen is in portrait orientation, the system applies the following layout, which
is saved at <code>res/layout/fragment_layout.xml</code>:</p>

<pre>&lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"&gt;
    &lt;fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
            android:id="@+id/titles"
            android:layout_width="match_parent" android:layout_height="match_parent" /&gt;
&lt;/FrameLayout&gt;</pre>

<p>This layout includes only <code>TitlesFragment</code>. This means that, when the device is in
portrait orientation, only the list of play titles is visible. So, when the user clicks a list
item in this configuration, the application will start a new activity to show the summary,
instead of loading a second fragment.</p>

<p>Next, you can see how this is accomplished in the fragment classes. First is <code>TitlesFragment</code>, which shows the list of Shakespeare play titles. This fragment extends <code><a href="../../../reference/android/app/ListFragment.html">ListFragment</a></code> and relies on it to handle most of the list view work.</p>

<p>As you inspect this code, notice that there are two possible behaviors when the user clicks a
list item: depending on which of the two layouts is active, it can either create and display a new
fragment to show the details in the same activity (adding the fragment to the <code><a href="../../../reference/android/widget/FrameLayout.html">FrameLayout</a></code>), or start a new activity (where the fragment can be shown).</p>

<pre>public static class TitlesFragment extends ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Populate list with our static array of titles.
        setListAdapter(new ArrayAdapter&lt;String&gt;(getActivity(),
                android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

        // Check to see if we have a frame in which to embed the details
        // fragment directly in the containing UI.
        View detailsFrame = getActivity().findViewById(R.id.details);
        mDualPane = detailsFrame != null &amp;&amp; detailsFrame.getVisibility() == View.VISIBLE;

        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }

        if (mDualPane) {
            // In dual-pane mode, the list view highlights the selected item.
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            // Make sure our UI is in the correct state.
            showDetails(mCurCheckPosition);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);
    }

    /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
    void showDetails(int index) {
        mCurCheckPosition = index;

        if (mDualPane) {
            // We can display everything in-place with fragments, so update
            // the list to highlight the selected item and show the data.
            getListView().setItemChecked(index, true);

            // Check what fragment is currently shown, replace if needed.
            DetailsFragment details = (DetailsFragment)
                    getFragmentManager().findFragmentById(R.id.details);
            if (details == null || details.getShownIndex() != index) {
                // Make new fragment to show this selection.
                details = DetailsFragment.newInstance(index);

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.details, details);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }

        } else {
            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Intent intent = new Intent();
            intent.setClass(getActivity(), DetailsActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);
        }
    }
}</pre>

<p>The second fragment, <code>DetailsFragment</code> shows the play summary for the item selected from
the list from <code>TitlesFragment</code>:</p>
 
<pre>public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist.  The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed.  Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;
        }

        ScrollView scroller = new ScrollView(getActivity());
        TextView text = new TextView(getActivity());
        int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                4, getActivity().getResources().getDisplayMetrics());
        text.setPadding(padding, padding, padding, padding);
        scroller.addView(text);
        text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
        return scroller;
    }
}</pre>

<p>Recall from the <code>TitlesFragment</code> class, that, if the user clicks a list item and the
current layout does <em>not</em> include the <code>R.id.details</code> view (which is where the
<code>DetailsFragment</code> belongs), then the application starts the <code>DetailsActivity</code>
activity to display the content of the item.</p>

<p>Here is the <code>DetailsActivity</code>, which simply embeds the <code>DetailsFragment</code> to display
the selected play summary when the screen is in portrait orientation:</p>

<pre>public static class DetailsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE) {
            // If the screen is now in landscape mode, we can show the
            // dialog in-line with the list so we don't need this activity.
            finish();
            return;
        }

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
        }
    }
}</pre>
 
<p>Notice that this activity finishes itself if the configuration is landscape, so that the main
activity can take over and display the <code>DetailsFragment</code> alongside the <code>TitlesFragment</code>.
This can happen if the user begins the <code>DetailsActivity</code> while in portrait orientation, but
then rotates to landscape (which restarts the current activity).</p>


<p>For more samples using fragments (and complete source files for this example),
see the sample code available in <a
href="../../../resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#Fragment">
ApiDemos</a> (available for download from the <a
href="../../../resources/samples/get.html">Samples SDK component</a>).</p>



    </div>

  <a href="#top" style="float:right">&uarr; Go to top</a>
  
    <p><a href="activities.html">&larr; Back to Activities</a></p>
  
  </div>

<div id="footer">


  <div id="copyright">
    
  Except as noted, this content is licensed under <a
  href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. 
  For details and restrictions, see the <a href="../../../license.html">
  Content License</a>.
  </div>
  <div id="build_info">
    
  Android 4.0&nbsp;r1 - 17 Oct 2011 18:17

  </div>

  <div id="footerlinks">
    
  <p>
    <a href="http://www.android.com/terms.html">Site Terms of Service</a> -
    <a href="http://www.android.com/privacy.html">Privacy Policy</a> -
    <a href="http://www.android.com/branding.html">Brand Guidelines</a>
  </p>
  </div>

</div> <!-- end footer -->

</div><!-- end doc-content -->

</div> <!-- end body-content --> 

<script type="text/javascript">
init(); /* initialize android-developer-docs.js */
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._trackPageview();
</script>

</body>
</html>



